package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Locale;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-10-06
 * Time:10:01
 */
public class TcpThreadEchoServer {
    private ServerSocket serverSocket = null;

    public TcpThreadEchoServer(int post) throws IOException {
        this.serverSocket = new ServerSocket(post);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        //建立连接，因为TCP是有连接的，就像接电话一样的操作，如果没有链接accept就会阻塞
        while (true) {
            Socket clientSocket = serverSocket.accept();
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }

    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.println("客户端已建立连接");
        try (InputStream inputStream = clientSocket.getInputStream()) {
            try (OutputStream outputStream = clientSocket.getOutputStream()) {
                Scanner in = new Scanner(inputStream);
                while (true) {
                    //1、从客户端读取请求
                    if (!in.hasNext()) {
                        System.out.printf("[%s,%d] 客户端断开连接！\n", clientSocket.getInetAddress(), clientSocket.getPort());
                        break;
                    }
                    String request = in.next();
                    //2、根据请求计算响应
                    String response = process(request);
                    //3、返回响应
                    //outputStream.write();
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.println(response);
                    //刷新缓冲区，如果没有该操作客户端不能第一时间看到响应结果
                    writer.flush();

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request.toUpperCase(Locale.ROOT);
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
    }
}
